import { AppDataSource } from '@/config/dataSource'
import { LicenseRecord } from '@/entity/License'
import { AuthService } from './auth'

class LicenseService {
    private static repository = AppDataSource.getRepository(LicenseRecord)

    // 创建配置
    static async create(data: Partial<LicenseRecord>, openid: string): Promise<LicenseRecord> {
        const existingConfig = await this.repository.findOne({ where: { license: data.license } })
        if (existingConfig) {
            throw new Error(`车牌号 ${data.license} 已存在`)
        }

        const user = await AuthService.getUserInfo(openid)
        const config = this.repository.create({
            ...data,
            user,
            openid,
            createdBy: openid,
            updatedBy: openid
        })

        return await this.repository.save(config)
    }

    // 更新配置
    static async update(data: Partial<LicenseRecord>, operator: string): Promise<LicenseRecord> {
        const result = await this.repository.findOne({ where: { license: data.license } })
        if (!result) {
            throw new Error(`车牌号 ${data.license} 不存在`)
        }

        result.updatedBy = operator
        result.time = data.time || ''
        result.phoneNumber = data.phoneNumber || ''

        return await this.repository.save(result)
    }

    // 删除配置
    static async delete(license: string): Promise<void> {
        const result = await this.repository.delete({ license })
        if (result.affected === 0) {
            throw new Error(`车牌号 ${license} 不存在`)
        }
    }

    // 获取单个配置
    static async findOne(license: string): Promise<LicenseRecord> {
        const result = await this.repository.findOne({ where: { license } })
        if (!result) {
            throw new Error(`车牌记录不存在`)
        }
        return result
    }

    // 获取所有配置
    static async findAll(where_params: Partial<LicenseRecord>): Promise<LicenseRecord[]> {
        const result = await this.repository.find({
            where: where_params,
            order: { createdAt: 'DESC' },
            select: {
                id: true,
                license: true,
                time: true,
                createdAt: true,
                updatedAt: true
            }
        })

        return result
    }
}

export default LicenseService
